package common.project.epic.ui;


import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;

import common.project.epic.db.CurrentUser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;

public class C2DMEpicReceiver extends BroadcastReceiver {

		protected static final String NOTIFY_C2DM_ID_URL = "http://epic.vidaleluca.com/notifyid.php";
		private Context context;

		@Override
		public void onReceive(Context context, Intent intent) {
			
			this.context = context;
			if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
		        handleRegistration(context, intent);
		    } else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
		        handleMessage(context, intent);
		    }
		} 
	
		private void handleMessage(Context context, Intent intent) {
			
		    Log.d("C2DMReceiver", intent.getStringExtra("payload"));
		    //receive a new Epic Version
		    CurrentUser.readCurrentUserSettings(context);
		    String username = CurrentUser.getCurrentUsername();
		    String url = intent.getStringExtra("payload");
		    performDownload(url, username);
		}

		private void handleRegistration(Context context2, Intent intent) {
			
			String registration = intent.getStringExtra("registration_id");
		    if (intent.getStringExtra("error") != null) {
		        // Registration failed, should try again later.
			    Log.d("c2dm", "registration failed");
			    String error = intent.getStringExtra("error");
			    if(error == "SERVICE_NOT_AVAILABLE"){
			    	Log.d("c2dm", "SERVICE_NOT_AVAILABLE");
			    }else if(error == "ACCOUNT_MISSING"){
			    	Log.d("c2dm", "ACCOUNT_MISSING");
			    }else if(error == "AUTHENTICATION_FAILED"){
			    	Log.d("c2dm", "AUTHENTICATION_FAILED");
			    }else if(error == "TOO_MANY_REGISTRATIONS"){
			    	Log.d("c2dm", "TOO_MANY_REGISTRATIONS");
			    }else if(error == "INVALID_SENDER"){
			    	Log.d("c2dm", "INVALID_SENDER");
			    }else if(error == "PHONE_REGISTRATION_ERROR"){
			    	Log.d("c2dm", "PHONE_REGISTRATION_ERROR");
			    }
		    } else if (intent.getStringExtra("unregistered") != null) {
		    	Log.d("c2dm", "unregistered");

		    } else if (registration != null) {
		    	Log.d("C2DMReceiver-onRegistered", "ID: "+registration);

		    	CurrentUser.readCurrentUserSettings(this.context);
			    String username = CurrentUser.getCurrentUsername();
			    notifyID(registration, username);
		    }
		}


		  
		private void performDownload(final String url, final String username) {
	
		        Thread t = new Thread() {
		 
		            public void run() {
		 
		                Looper.prepare();
		 
		                DefaultHttpClient client = new DefaultHttpClient();
		 
		                HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);                
		 
		                HttpResponse response;
		 
		                HttpEntity entity;        
		 
		                try {
		 
		                    HttpPost post = new HttpPost(url);
		 
		                    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		 
		                    nvps.add(new BasicNameValuePair("username", username));
		 
		                    
		                    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		                    post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		 
		                    response = client.execute(post);
		 
		                    entity = response.getEntity();
		                    
		                    if (entity != null) entity.consumeContent();
		                    
		                } catch (Exception e) {
		 
	
		 
		                }
		 
		                Looper.loop();                
		 
		            }
		 
		        };
		 
		        t.start();
		 
		    }
		  
		private void notifyID(final String c2dm_id, final String username) {
				 
		        
		        Thread t = new Thread() {
		 
		            public void run() {
		 
		                Looper.prepare();
		 
		                DefaultHttpClient client = new DefaultHttpClient();
		 
		                HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);                
		 
		                HttpResponse response;
		 
		                HttpEntity entity;        
		 
		                try {
		 
		                    HttpPost post = new HttpPost(NOTIFY_C2DM_ID_URL);
		 
		                    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
	
		                    nvps.add(new BasicNameValuePair("username", username));
		 
		                    nvps.add(new BasicNameValuePair("id", c2dm_id));
		 
		                    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		                    post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		 
		                    response = client.execute(post);
		 
		                    entity = response.getEntity();
		                    
		                    Log.d("C2DM UPDATE RESPONSE", response.toString());
		                    
		                    if (entity != null) entity.consumeContent();
		                    
		                } catch (Exception e) {
		 
		                    Log.d("notify C2DM ID", "sending notify Id Exception");
		                    
		                }
		 
		                Looper.loop();                
		 
		            }
		 
		        };
		 
		        t.start();
		 
		    }


		
}
